package cn.gailvlun.gll.presentation.hotel.day

import android.databinding.DataBindingUtil
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.PagerSnapHelper
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import cn.gailvlun.gll.R
import cn.gailvlun.gll.databinding.FragmentHotelTemplateBinding
import cn.gailvlun.gll.net.*
import cn.gailvlun.gll.net.hotel.InsomniaCategory
import cn.gailvlun.gll.presentation.base.BaseFragment
import cn.gailvlun.gll.util.DialogUtil
import cn.gailvlun.gll.util.IsEmpty
import cn.gailvlun.gll.util.RxUtil
import cn.gailvlun.gll.util.ToastUtil
import com.freeze.horizontalrefreshlayout.lib.HorizontalRefreshLayout
import com.freeze.horizontalrefreshlayout.lib.RefreshCallBack
import com.freeze.horizontalrefreshlayout.lib.refreshhead.MaterialRefreshHeader


class HotelTemplateFragment : BaseFragment(), RefreshCallBack {
    companion object {
        fun newInstance(category: InsomniaCategory): HotelTemplateFragment {
            return HotelTemplateFragment().apply {
                this.arguments = Bundle().apply {
                    putSerializable("insomniaCategory", category)
                }
            }
        }
    }

    override fun isLazyLoad() = true

    private lateinit var mBinding: FragmentHotelTemplateBinding
    private lateinit var mAdapter: HotelTemplateAdapter
    private lateinit var mLayoutManager: ScaleTemplateLayoutManager
    private lateinit var mPagerSnapHelper: PagerSnapHelper
    private lateinit var mInsomniaCategory: InsomniaCategory

    private val newQueryParam = NewQueryParam()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        mInsomniaCategory = arguments.getSerializable("insomniaCategory") as InsomniaCategory
    }

    override fun initComponent(inflater: LayoutInflater, container: ViewGroup?): View {
        mBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_hotel_template, container, false)

        mBinding.presenter = Presenter()
        mAdapter = HotelTemplateAdapter(mContext)
        mBinding.recyclerView.adapter = mAdapter

        mLayoutManager = ScaleTemplateLayoutManager(mContext)
        mLayoutManager.orientation = LinearLayoutManager.HORIZONTAL
        mBinding.recyclerView.layoutManager = mLayoutManager

        mPagerSnapHelper = PagerSnapHelper()
        mPagerSnapHelper.attachToRecyclerView(mBinding.recyclerView)

        mBinding.hrl.setRefreshMode(HorizontalRefreshLayout.MODE_UNDER_FOLLOW_DRAG)
        mBinding.hrl.setRefreshHeader(MaterialRefreshHeader(HorizontalRefreshLayout.START), HorizontalRefreshLayout.START)
        mBinding.hrl.setRefreshHeader(MaterialRefreshHeader(HorizontalRefreshLayout.END), HorizontalRefreshLayout.END)
        mBinding.hrl.isEnable = true

        mBinding.hrl.setRefreshCallback(this)

        return mBinding.root
    }

    override fun createHandler() {

    }

    override fun loadData(savedInstanceState: Bundle?) {
        mBinding.hrl.startAutoRefresh(true)
    }

    override fun onLeftRefreshing() {
        HttpMethods.getHotelService()
                .getTemplate(mInsomniaCategory, null, null, null)
                .compose(RxUtil.applyScheduler())
                .compose(bindToLifecycle())
                .subscribe(object : HttpSubscriber<ListRes<HotelTemplate>>() {
                    override fun onSuccess(response: ListRes<HotelTemplate>?) {
                        mAdapter.set(response?.results)
                    }

                    override fun onFailure(errMsg: String?, response: ListRes<HotelTemplate>?, code: Int) {
                        DialogUtil.showError(mContext, errMsg)
                    }

                    override fun onFinish() {
                        super.onFinish()
                        mBinding.hrl.onRefreshComplete()
                    }
                })
    }

    override fun onRightRefreshing() {
        newQueryParam.lastId = mAdapter.getLastId()

        HttpMethods.getHotelService()
                .getTemplate(mInsomniaCategory, newQueryParam.lastId, newQueryParam.direction, null)
                .compose(RxUtil.applyScheduler())
                .compose(bindToLifecycle())
                .subscribe(object : HttpSubscriber<ListRes<HotelTemplate>>() {
                    override fun onSuccess(response: ListRes<HotelTemplate>?) {
                        if (!IsEmpty.list(response?.results)) {
                            mAdapter.addAll(response?.results)
                        } else {
                            ToastUtil.showShort(getString(R.string.hotel_template_refresh_warning))
                        }
                    }

                    override fun onFailure(errMsg: String?, response: ListRes<HotelTemplate>?, code: Int) {
                        DialogUtil.showError(mContext, errMsg)
                    }

                    override fun onFinish() {
                        super.onFinish()
                        mBinding.hrl.onRefreshComplete()
                    }
                })
    }

    fun getCurrentTemplate(): HotelTemplate? {
        val currentPos = mBinding.recyclerView.getChildAdapterPosition(mPagerSnapHelper.findSnapView(mLayoutManager))
        return mAdapter.getData().getOrNull(currentPos)
    }


    inner class Presenter {
        fun previous() {
            val findFirstVisibleItemPosition = mLayoutManager.findFirstVisibleItemPosition()
            mBinding.recyclerView.smoothScrollToPosition(if (findFirstVisibleItemPosition > 0) findFirstVisibleItemPosition - 1 else 0)
        }

        fun next() {
            val findFirstVisibleItemPosition = mLayoutManager.findFirstVisibleItemPosition()
            mBinding.recyclerView.smoothScrollToPosition(if (findFirstVisibleItemPosition < mAdapter.getData().size) findFirstVisibleItemPosition+1 else mAdapter.getData().size-1)
        }

    }

}